import time

from django.core.exceptions import ValidationError
from django.db import IntegrityError
from django.db.models import Q
from django.shortcuts import render, redirect
from django.http.response import HttpResponse
from django.urls import reverse

from .models import User
from app01.views import transfer_the_page_range
from django.core.paginator import Paginator
from django.core.paginator import EmptyPage, PageNotAnInteger


# Create your views here.


def user_manage(request):
    cases = User.objects.all().order_by("-id")
    p = request.GET.get('current_page', 1)
    paginator = Paginator(cases, 10)
    p = int(p)
    page_range = transfer_the_page_range(p, paginator)
    if paginator.num_pages - p > 5:
        last_page = True
    try:
        pages = paginator.page(p)
    except PageNotAnInteger:
        pages = paginator.page(1)
    except EmptyPage:
        pages = paginator.page(paginator.num_pages)
    return render(request, 'userManage/index.html', locals())


# TODO 用户新增
def create_user(request):
    try:
        if request.method == 'POST':
            referer = request.headers.get('Referer')
            user_name = request.POST.get('user_name')
            bu = request.POST.get('BU')
            remarks = request.POST.get('remarks')
            create_time = request.POST.get('create_time')
            user = User.objects.all()
            user.create(
                user_name=user_name, user_bu=bu, create_time=create_time, remarks=remarks
            )
            return redirect(referer)
        else:
            return HttpResponse("demo")
    except IntegrityError:
        return HttpResponse("用户名称重复，请修改后再次提交！")


def search_user(request):
    try:
        if request.method == 'GET':
            start_date = request.GET.get("start_date", '')
            end_date = request.GET.get("end_date", '')
            user_name = request.GET.get('user_name', '')
            user_name = user_name.strip()
            user_bu = request.GET.get('user_bu', '')
            user_bu = user_bu.strip()
            if start_date and end_date:
                search_result = User.objects.filter(Q(create_time__gte=start_date + " 00:00:00") &
                                                    Q(create_time__lte=end_date + " 23:59:59"),
                                                    user_name__contains=user_name,
                                                    user_bu__contains=user_bu).order_by('-id')
            elif start_date:
                search_result = User.objects.filter(create_time__gte=start_date + " 00:00:00",
                                                    user_name__contains=user_name,
                                                    user_bu__contains=user_bu).order_by('-id')
            elif end_date:
                search_result = User.objects.filter(create_time__lte=end_date + " 23:59:59",
                                                    user_name__contains=user_name,
                                                    user_bu__contains=user_bu).order_by('-id')
            else:
                search_result = User.objects.filter(user_name__contains=user_name,
                                                    user_bu__contains=user_bu).order_by('-id')
            p = request.GET.get('current_page', 1)
            p = int(p)
            paginator = Paginator(search_result, 10)
            page_range = transfer_the_page_range(p, paginator)
            if paginator.num_pages - p > 5:
                last_page = True
            try:
                pages = paginator.page(p)
            except PageNotAnInteger:
                pages = paginator.page(1)
            except EmptyPage:
                pages = paginator.page(paginator.num_pages)
            return render(request, 'userManage/search.html', locals())
    except ValidationError as error1:
        return render(request, 'app01/500_error.html', {"error_message": "年份不能超过4位数"})


def edit_user(request):
    if request.method == 'POST':
        referer = request.headers.get('Referer')
        user_id = request.POST.get('user_id')
        user_id = int(user_id)
        user_name = request.POST.get('user_name')
        user_bu = request.POST.get('user_bu')
        update_time = time.strftime("%Y-%m-%d %H:%M:%S")
        remarks = request.POST.get('remarks')
        user = User.objects.filter(id=user_id)
        try:
            user.update(user_name=user_name, update_time=update_time, user_bu=user_bu,
                        remarks=remarks)
            return redirect(referer)
        except IntegrityError as error1:
            return HttpResponse("用户名称重复，请修改后再次提交！")


def delete_user(request, user_id):
    User.objects.get(pk=user_id).delete()
    referer = request.headers.get('Referer')
    return redirect(referer)
